import json
import re

import pdfplumber

import common

__TAG = "MccEx"
__FIELDS = ["Code", "ExTbl"]
__SERVER = common.ServerRemoteRelease
__INPUT = '/home/zhujianfeng/文档/drgs_2_2.pdf'
__OUTPUT = 'out/MccExclude.txt'

def pdf_to_text():
    txt = ""
    with pdfplumber.open(__INPUT) as pdf:
        for page in pdf.pages:
            print(page.page_number)
            if page.page_number < 1208 or page.page_number > 1507:
                continue
            txt+=page.extract_text()
    with open(__OUTPUT, 'w', encoding='utf-8') as file:
        file.write(txt)

def append():
    table_pattern = re.compile(r'^表\d+-\d+-\d+')
    icd_10_code_pattern = re.compile(r'^[A-Z]\d+(\.\d+)(x\d+)*(\+\S+\*)*')
    with open(__OUTPUT, 'r', encoding='utf-8') as file:
        records = []
        for line in file:
            spans = line.split(" ")
            match = len(spans)==3 and re.match(icd_10_code_pattern,spans[0].strip()) and re.match(table_pattern, spans[2].strip())
            if match:
                records.append({
                    __FIELDS[0]: spans[0].strip().replace('+', '†'),
                    __FIELDS[1]: spans[2].strip()
                })
            if len(records) > 0 and len(records) % 100 == 0:
                msg = json.dumps({
                    "fields": __FIELDS,
                    "records": records
                }, ensure_ascii=False)
                print(msg)
                common.batch_add(__TAG, msg, __SERVER)
                records.clear()
        if len(records) > 0:
            msg = json.dumps({
                "fields": __FIELDS,
                "records": records
            }, ensure_ascii=False)
            print(msg)
            common.batch_add(__TAG, msg, __SERVER)


def export_map():
    arm = common.export_grouped_fv(__TAG, __FIELDS[0], __FIELDS[1], print_res=False, server=__SERVER)
    arm = json.loads(arm)
    # print(arm)
    tbl_dict = arm['data']
    # print(tbl_dict)
    return tbl_dict

if __name__ == '__main__':
    # pdf_to_text()
    # append()
    export_map()